package com.cps116.friendstracker;

import java.util.ArrayList;
import java.util.List;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
import java.sql.ResultSet;

import com.cps116.parcelables.Coordinate;
import com.cps116.parcelables.LocationTraceList;
import com.cps116.parcelables.MapParcelableData;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.*;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;
import android.database.Cursor;
import android.database.sqlite.*;
import android.database.sqlite.SQLiteDatabase.CursorFactory;

public class FriendsLocationLiveUpdateService extends Service{

	public static final long INFINITE_TIME_UPDATE = Long.MAX_VALUE;

	private GroupLocationsUpdater updater;
	private long groupUpdatePreference;
	private boolean runFlag;


	@Override
	public void onCreate() {
		super.onCreate();	
		groupUpdatePreference= INFINITE_TIME_UPDATE;		
	}


	@Override
	public IBinder onBind(Intent intent) {
		return null;
	}


	@Override
	public void onStart(Intent intent, int startId) {
		super.onStart(intent, startId);		
		//fetch the service related data...
		groupUpdatePreference = intent.getLongExtra("delay_interval", Long.MAX_VALUE);
		runFlag = intent.getBooleanExtra("run_flag", false);

		
		//start the thread updater thing										
		updater = new GroupLocationsUpdater(groupUpdatePreference);		
		updater.start();		
	
	}

	//	>version 1.6+...omitted ...
	//	@Override
	//	public int onStartCommand(Intent intent, int flags, int startId) {
	//		return super.onStartCommand(intent, flags, startId);
	//		
	//
	//	}


	@Override
	public void onDestroy() {
		super.onDestroy();
		
		//stop thread service...make it easie to stop the thread service...
		updater.interrupt();		
		updater = null;			
	}


	public boolean getServiceRunFlag() {
		return runFlag;
	}


	public void setServiceRunFlag(boolean runFlag) {
		this.runFlag = runFlag;
	}



	private class GroupLocationsUpdater extends Thread {

		//check if this is set up before the constructor call
		private long delay = Long.MAX_VALUE;
		private FriendsLocationLiveUpdateService locationServiceCaller;

		public GroupLocationsUpdater(long delay)
		{
			super("group-locations-updater-thread");
			this.delay = delay;
		}


		@Override
		public void run() {
			//set the service Caller here
			locationServiceCaller = FriendsLocationLiveUpdateService.this;

			Log.d("testing", "update service started");

			while(locationServiceCaller.getServiceRunFlag())
			{
				try{
					//you want to make sure the first you do is sleep for the delayed time
					Thread.sleep(delay);
					Log.d("FriendsLocationLiveUpdateService", "thread is running");

					//Here's where you put in all the http post request....
					//you want to check for any update...
					
					String URL = "";
			
					List<MapParcelableData> dataList = new ArrayList<MapParcelableData>();
					//you simply want to populate this list....
					
					try 
					{
						SQLiteDatabase db = SQLiteDatabase.openDatabase(URL, null , 268435456);
						Cursor resp = db.rawQuery("SELECT user_id FROM Location_History", null);
						Log.d("FriendsLocationLiveUpdateService",resp.getColumnName(0));
						
						
					}
					catch(Exception e)
					{
						
					}
					
					HttpClient httpclient = new DefaultHttpClient();
					HttpPost httppost = new HttpPost("http://www.yoursite.com/script.php");

					 try {
					        // Add your data
					        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
					        nameValuePairs.add(new BasicNameValuePair("id", "12345"));
					        nameValuePairs.add(new BasicNameValuePair("stringdata", "AndDev is Cool!"));
					        httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

					        // Execute HTTP Post Request
					        HttpResponse response = httpclient.execute(httppost);
					        
					        
					        
					    } catch (Exception e) {
					        // TODO Auto-generated catch block
					    }
					
					
					
					
					
					
					
					//TODO: --- IDK: maybe you can't call an activity's inner class through running on a separate thread...
					//might have to do asynctask
					
					//you just want to put tracelist 
					LocationTraceList traceList = new LocationTraceList(dataList);					
					Intent newFriendsLocationUpdateIntent = new Intent("com.cps116.FRIENDS_LOCATION_UPDATE");
					newFriendsLocationUpdateIntent.putExtra("live_update_coordinates", traceList);
					//you want to send broadcast heress
					locationServiceCaller.sendBroadcast(newFriendsLocationUpdateIntent);

				} 
				catch (InterruptedException e)
				{
					//end the thread...
					locationServiceCaller.setServiceRunFlag(false);
				}
			}
		}

		@Override
		public synchronized void start() {
			super.start();
		}

		@Override
		public void destroy() {
			super.destroy();
			Log.d("FriendsLocationLiveUpdateService", "thread update service terminated");
		}
	}



}
